package com.sq.partner.manager.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.mybatis.model.ChannelBusinessReal;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.ChannelBusinessRealService;
import com.sq.partner.manager.service.DictManagerService;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * 
 * @date 2019-12-2 合作伙伴渠道分类
 *
 */
@Controller
@RequestMapping("/channelClassification")
public class ChannelClassificationController {
	private static Logger logger = LogUtil.getLog(ChannelClassificationController.class);

	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	@Autowired
	private ChannelBusinessRealService channelBusinessRealService;
	@Autowired
	private DictManagerService dictManagerService;
	/**
	 * 跳转合作伙伴渠道分来列表页面
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	public String list(ModelMap model) throws Exception{
		List<DictDto> channelClassification = DictCache.getDict(Constants.CHANNEL_CLASSIFICATION);
		model.put("channelClassification", channelClassification);
		logger.debug("forward ChannelClassification successful....跳转合作伙伴渠道分类页面");
		return "nlifeProduct/channelClassification/list";
	}
	/**
	 * 分页条件查询channelClassification
	 * @param pageIndex 当前页码
	 * @param channelCode 合作伙伴代码
	 * @param businessChannelType 合作伙伴渠道类型
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/queryByCriteria1")
	@ResponseBody
	public Page<Map<String,Object>> queryByCriteria1(HttpSession session, Integer pageIndex,Integer size,String channelName,String channelCode,String businessChannelType) throws Exception{
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelName(channelName);
		channelInfo.setChannelCode(channelCode);
	    channelInfo.setBusinessChannelType(businessChannelType);
		logger.debug("当前页码："+pageIndex+"，合作伙伴名称："+channelName+"，合作伙伴代码："+channelCode+"，合作伙伴渠道类型："+businessChannelType);
		//总行和分行
		boolean isHQFlag = false;
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			isHQFlag = user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE);
		}
		if (null!=user) {
			user.setHQFlag(isHQFlag);
		}
		
		Page<Map<String,Object>> channelInfoPage = channelInfoConfigService.queryByCriteria1(pageIndex, size,channelInfo, user,businessChannelType);
		return channelInfoPage;
	}
	/**
	 * 跳转合作伙伴渠道分来列表页面
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/classificationInfo")
	public String classificationInfo(ModelMap model) throws Exception{
		return "nlifeProduct/channelClassification/classificationInfo";
	}
	/**
	 * 分页条件查询ChannelClassification
	 * 从缓存字典表中取值
	 * @param pageIndex
	 * @param size
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/queryClassificationInfo")
	@ResponseBody
	public Page<DictDto> queryChannelClassification(HttpSession session,Page<DictDto> page) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("codeType", "channel_classification");
		map.put("BEGINROW", (page.getCurrent()-1) * page.getSize());
		map.put("ENDROW", page.getCurrent() * page.getSize());
		page.setMap(map);
		page=dictManagerService.queryDictDtoPageByCriteria(page);
		return page;
	}
	
	/**
	 * 更新字典表中的CODE_TYPE=channel_classification
	 */
	@RequestMapping(value = "/updateDict")
	@ResponseBody
	public  Page<DictDto> updateDict(DictDto dict,Page<DictDto> page) throws Exception {
		logger.debug("进入Controller >>>>> /channelClassification/updateDict");
		if (StrUtil.isEmpty(dict.getCodeType())) {
			page.setMessage("险种类别不能为空");
			page.setResult("error");
			return page;
		}

		if (StrUtil.isEmpty(dict.getCode())) {
			page.setMessage("字典值不能为空");
			page.setResult("error");
			return page;
		}
		
		dictManagerService.updateGatewayDict(dict);
		page.setMessage("更新成功");
		DictCache.refreshCache();
		return page;
	} 
	
	/**
	 * 导出合作伙伴渠道分类
	 */
	@RequestMapping(value="/downloadClassification")
	public void downloadQueryChannelClassification (HttpSession session, HttpServletResponse response,String channelName,String channelCode,String businessChannelType,String deptCode,String transType)throws Exception{
		logger.debug("******进入导出信息*********");
		Integer pageIndex = 1,size = 1000;//默认取第一页数据，每页查询1000条数据
		Page<Map<String, Object>> channelInfoPage = queryByCriteria1(session, pageIndex,size,channelName,channelCode,businessChannelType);
		List<Map<String, Object>> channelClassificationList = channelInfoPage.getData();//存第一页数据（小于等于1000条）
		int maxPag = channelInfoPage.getMaxPage();
		for(int i=2;i<=maxPag;i++){
			channelClassificationList.addAll(queryByCriteria1(session, i,size,channelName,channelCode,businessChannelType).getData());
		}
		channelBusinessRealService.downloadQueryChannelClassification(channelClassificationList,response);
	}
	/**
	 * 保存数据到t_CHANNEL_BUSINESS_REAL表
	 */
	@RequestMapping(value = "/saveOrUpdateClassification")
	@ResponseBody
	public  Page<DictDto> saveOrUpdateClassification(ChannelBusinessReal channelBusinessReal,Page<DictDto> page) throws Exception {
		logger.debug("进入Controller >>>>> /channelClassification/saveOrUpdateClassification");
		if (StrUtil.isEmpty(channelBusinessReal.getChannelCode())) {
			page.setMessage("合作伙伴代码不能为空!");
			page.setResult("error");
			return page;
		}

		if (StrUtil.isEmpty(channelBusinessReal.getBusinessChannelType())) {
			page.setMessage("合作伙伴渠道类型不能为空!");
			page.setResult("error");
			return page;
		}
		//查询表中是否存在当前合作伙伴的信息
		ChannelBusinessReal channel = this.channelBusinessRealService.queryChannelBusinessReal(channelBusinessReal.getChannelCode());
		//若不存在,则执行insert操作
		if(channel == null) {
			this.channelBusinessRealService.insertChannelBusinessReal(channelBusinessReal);
		}else {//若存在,则执行update操作
			this.channelBusinessRealService.updateChannelBusinessRealNotNull(channelBusinessReal);
		}
		page.setMessage("保存成功");
		return page;
	} 
}
